package com.nginxmanager.controller;

import com.nginxmanager.domain.Conf;
import com.nginxmanager.domain.System;
import com.nginxmanager.server.ConfRepository;
import com.nginxmanager.server.config.nginxConf.AllNginxConf;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018-01-16.
 */
@RestController
@RequestMapping("/nginx")
@Api(tags = "Nginx配置项数据库操作Api")
public class ConfSqlcontroller {
    @Autowired
    ConfRepository confRepository;
    private AllNginxConf nginxConf = new AllNginxConf();

    @GetMapping("/getConfSql")
    @ApiOperation("查看数据库中配置项")
    public ResponseEntity<List<Conf>> getbypage (@RequestParam("page")int page,@RequestParam("size")int size){
        PageRequest pageRequest = new PageRequest(page,size,null);
        Page<Conf> confs = confRepository.findAll(pageRequest);
        return ResponseEntity.status(200).body(confs.getContent());
    }

    @GetMapping("/getConfSqlByModel")
    @ApiOperation("查看数据库中配置项")
    public ResponseEntity<List<Conf>> getbymodel (@RequestParam("page")int page,@RequestParam("size")int size,@RequestParam("model")String model){
//         confs = new ArrayList<>();
        PageRequest pageRequest = new PageRequest(page,size,null);
        Page<Conf> confs = confRepository.findByModel(pageRequest,model);
        return ResponseEntity.status(200).body(confs.getContent());
    }


    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @PostMapping("/postConfSql")
    @ApiOperation(value="添加数据库中配置项")
    @ApiResponses(value={
            @ApiResponse(code = 401, message = " id必须为空"),
            @ApiResponse(code = 200, message = " 保存成功"),
    })
    public ResponseEntity<Void> postConfSql(@RequestBody Conf conf) throws Exception{
        if (conf.getId()!=null) {
            return  ResponseEntity.status(401).body(null);
        }
        confRepository.save(conf);
        return  ResponseEntity.status(200).body(null);
    }

    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @DeleteMapping("/deleConfSql")
    @ApiOperation(value="添加数据库中配置项")
    @ApiResponses(value={
            @ApiResponse(code = 200, message = " 删除成功"),
    })
    public ResponseEntity<Void> deleConfSql(@RequestParam("id")Integer confId,@RequestParam("address")String address) throws Exception{

        Conf conf = confRepository.findOne(confId);
        nginxConf.delete(address,conf);
        confRepository.delete(confId);
        return  ResponseEntity.status(200).body(null);
    }
}
